<template>
  <view class="page">
    <CommonNavbar
      title="新建班级"
      :showBack="true"
    ></CommonNavbar>
    <view class="main">
      <up-form
        labelWidth="200rpx"
        labelPosition="left"
        :model="state.classInfo"
        :rules="state.rules"
        errorType="toast"
        ref="uFormRef"
      >
        <up-form-item
          label="班级名称"
          prop="className"
        >
          <up-input
            v-model="state.classInfo.className"
            placeholder="请输入班级名称"
            border="none"
            inputAlign="right"
          ></up-input>
        </up-form-item>
        <up-form-item
          label="年级"
          prop="grade"
        >
          <up-text
            :text="state.classInfo.grade || '请选择年级'"
            align="right"
            :color="`${state.classInfo.grade ? 'black' : '#b7b7b7'}`"
            @click="state.showPicker = true"
          >
          </up-text>
        </up-form-item>
      </up-form>
    </view>
    <view class="footer">
      <up-button
        type="primary"
        text="创建班级"
        @click="submit"
        :loading="state.isLoading"
      ></up-button>
    </view>
    <!-- 年级选择弹窗 -->
    <up-picker
      :show="state.showPicker"
      :columns="gradeOptions"
      confirmColor="#6D9319"
      @confirm="onGradeConfirm"
    ></up-picker>
  </view>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { createClassApi } from '@/api/classes';
const uFormRef = ref(null);
const gradeOptions = ref([['一年级', '二年级', '三年级', '四年级', '五年级', '六年级']]); // 年级选项

const state = reactive({
  showPicker: false,
  classInfo: {
    className: '',
    grade: ''
  },
  isLoading: false,
  rules: {
    className: {
      required: true,
      message: '请输入班级名称',
      trigger: 'blur'
    },
    grade: {
      required: true,
      message: '请选择年级',
      trigger: 'blur'
    }
  }
});
const submit = () => {
  uFormRef.value.validate().then(async (valid) => {
    if (valid) {
      state.isLoading = true;
      const params = {
        ...state.classInfo
      };
      const result = await createClassApi(params);
      if (result.code === 200) {
        state.isLoading = false;
        uni.navigateTo({
          url: '/pages-sub/teacher/classes'
        });
      } else {
        state.isLoading = false;
        uni.$u.toast(result.msg);
      }
    }
  });
};
const onGradeConfirm = (e) => {
  console.log('e', e);
  state.classInfo.grade = e.value[0];
  state.showPicker = false;
};
</script>

<style></style>
